import 'package:flutter/material.dart' hide NavigationBar;
import 'package:hi_base/hi_state.dart';
import 'package:hi_base/view_util.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:smart/http/dao/home_dao.dart';
import 'package:smart/model/home_mo.dart';
import 'package:smart/navigator/hi_navigator.dart';
import 'package:smart/page/home_tab_page.dart';
import 'package:smart/page/profile_page.dart';
import 'package:smart/page/video_detail_page.dart';
import 'package:smart/util/toast.dart';
import 'package:smart/widget/LoadingContainer.dart';
import 'package:smart/widget/navigation_bar.dart';

import '../widget/hi_tab.dart';

class HomePage extends StatefulWidget {
  final ValueChanged<int>? onJumpTo;

  const HomePage({key, this.onJumpTo}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends HiState<HomePage>
    with
        AutomaticKeepAliveClientMixin,
        TickerProviderStateMixin,
        WidgetsBindingObserver
   {
  //AutomaticKeepAliveClientMixin 是为了 重写wantKeepAlive 方法，返回界面时候不会 重写走onStart 方法
  var listener;
  //var tabs = ['推荐', '热门', '追播', '影视', '高效', '日常', '综合', '手机游戏', '短片*手书*配音'];
  List<CategoryMo> categoryList = [];
  List<BannerMo> bannerList = [];

  TabController? _controller;

  bool _isLoading = true;
  Widget? _currentPage;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); //对生命周期进行监听
    _controller = TabController(length: categoryList.length, vsync: this);
    // 界面初始化的时候  注册监听
    HiNavigator.getInstance().addListener(this.listener = (current, pre) {
      this._currentPage = current.page;
      print('current:${current.page}');
      print('pre:${pre.page}');
      if (widget == current.page || current.page is HomePage) {
        print('打开了首页:onResume');
      } else if (widget == pre.page || pre.page is HomePage) {
        print('首页:onPause 方法');
      }
      //当页面返回到首页，恢复首页状态栏样式
      if (pre.page is VideoDetailPage && !(current.page is ProfilePage)) {
        var statusStyle = StatusStyle.DARK_CONTENT;
        changeStatusBar(color: Colors.white, statusStyle: statusStyle);
      }
    });

    loadData();
  }

  @override
  void dispose() {
    super.dispose();
    print(' HomePage  dispose ');
    //界面销毁的时候移除监听
    WidgetsBinding.instance.removeObserver(this); //对生命周期进行监听
    HiNavigator.getInstance().removeListener(this.listener);
    _controller?.dispose(); // 用到了 controller,那么在界面销毁的时候 释放掉 controller
  }

  //监听应用程序生命周期的变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print(':didChangeAppLifecycleState:$state');
    switch (state) {
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.resumed:
        if (!(_currentPage is VideoDetailPage)) {           //适配状态栏
          changeStatusBar(
              color: Colors.white, statusStyle: StatusStyle.DARK_CONTENT);
        }
        break;
      case AppLifecycleState.paused:
        break;
      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.hidden:
      // TODO: Handle this case.
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        // appBar: AppBar(),
        body: LoadingContainer(
      isLoading: _isLoading,
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          NavigationBar(
              height: 50,
              child: _appBar(),
              color: Colors.white,
              statusStyle: StatusStyle.DARK_CONTENT),
          Container(
            // color: Colors.white,
            padding: EdgeInsets.only(top: 5),
            child: _tabBar(),
            decoration: bottomBoxShadow(),
          ),
          Flexible(
              child: TabBarView(
            controller: _controller,
            children: categoryList.map((tab) {
              return HomeTabPage(
                  categoryName: tab.name!!,
                  bannerList: tab.name == '推荐'
                      ? bannerList
                      : null); //只有在推荐的时候，才会传递 banner 数据过去
            }).toList(),
          ))
        ],
      ),
    ));
  }
  /*
     Text('首页'),
          MaterialButton(
            color: Color.fromARGB(255, 241, 207, 219),
            //onPressed: () => widget.onJumpToDetail!(VideoModel(123)),
            onPressed: () => {
              HiNavigator.getInstance().onJumpTo(RouteStatus.detail,
                  args: {'videoMo': VideoModel(101)})
            },
            ///配制按钮上文本或者图标的颜色
            textColor: Colors.black,
            ///按钮点击下的颜色
            highlightColor: Colors.yellow,
            ///水波方的颜色
            splashColor: Colors.green,
            ///按钮的阴影
            elevation: 10,
            ///按钮按下时的阴影高度
            highlightElevation: 20,
            ///未设置点击时的阴影高度
            disabledElevation: 5.0,
            child: Column(
              children: [Text("详情")],
            ),
          )
   */

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true; // 保证生命周期不会重走

  _tabBar() {
    return HiTab(
      categoryList.map<Tab>((tab) {
        return Tab(text: tab.name);
      }).toList(),
      controller: _controller,
      fontSize: 16,
      boderWidth: 3,
      unselectedLabelColor: Colors.black54,
      insets: 13,
    );

    /* return TabBar(
        controller: _controller,
        isScrollable: true, //是否可以滑动
        labelColor: Colors.black,
        indicator: UnderlineIndicator(
          strokeCap: StrokeCap.round,
          borderSide: BorderSide(color: primary, width: 3),
          insets: EdgeInsets.only(left: 15, right: 15),
        ),
        tabs: categoryList.map<Tab>((tab) {
          return Tab(
            child: Padding(
              padding: EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
              child: Text(
                tab.name!!,
                style: TextStyle(fontSize: 16),
              ),
            ),
          );
        }).toList());*/
  }

  void loadData() async {
    print('加载数据 loadData');
    try {
      HomeMo result = await HomeDao.get('推荐');
      print('loadData:$result');
      if (result.categoryList != null) {
        // tab 长度发生变化 需要重新创建TabController
        _controller =
            TabController(length: result.categoryList!.length, vsync: this);
      }
      setState(() {
        categoryList = result.categoryList!;
        bannerList = result.bannerList!;
        _isLoading = false; //界面第一次进来时候，加载完数据就 设置为false
      });
    } on NeedAuth catch (e) {
      print('HomePage   NeedAuth ');
      print(e);
      _isLoading = false;
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print('HomePage   HiNetError ');
      print(e);
      _isLoading = false;
      showWarnToast(e.message);
    }
  }

  _appBar() {
    return Padding(
      padding: EdgeInsets.only(left: 15, right: 15),
      child: Row(
        children: [
          InkWell(
            onTap: () {
              print('_appBar  onTap');
              if (widget.onJumpTo != null) {
                widget.onJumpTo!(3);
              }
            },
            child: ClipRRect(
              //裁剪成圆形
              borderRadius: BorderRadius.circular(23),
              child: Image(
                height: 45,
                width: 46,
                image: AssetImage('images/avatar.png'),
              ),
            ),
          ),
          Expanded(
              child: Padding(
            padding: EdgeInsets.only(left: 15, right: 15),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Container(
                padding: EdgeInsets.only(left: 10),
                height: 32,
                alignment: Alignment.centerLeft,
                child: Icon(Icons.search, color: Colors.grey),
                decoration: BoxDecoration(color: Colors.grey[100]),
              ),
            ),
          )),
          Icon(Icons.explore_outlined, color: Colors.grey),
          Padding(
            padding: EdgeInsets.only(left: 12),
            child: Icon(
              Icons.mail_outline,
              color: Colors.grey,
            ),
          )
        ],
      ),
    );
  }
}
